package com.gf.framework.weblog.service;

import com.gf.framework.mongo.service.GfMongoTemplate;
import com.gf.framework.weblog.model.WebLogInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author gaofei
 * @date 2022/6/13 21:45
 */
@Component
@Slf4j
public class WebLogServiceImpl extends GfMongoTemplate<WebLogInfo> {
    private final LinkedBlockingQueue<WebLogInfo> webLogInfos = new LinkedBlockingQueue<>(1000);

    public void send(WebLogInfo webLogInfo) {
        webLogInfos.offer(webLogInfo);
    }

    @Scheduled(fixedRate = 1000)
    public void saveLog() {
        int maxSize = webLogInfos.size();
        List<WebLogInfo> tempList = new ArrayList<>(maxSize);
        while (tempList.size() < maxSize) {
            tempList.add(webLogInfos.poll());
        }
        try {
            saveBatch(tempList);
        } catch (Exception e) {
            log.error("写入autolog失败:", e);
        }
    }
}
